package com.opencv.demo;

import org.opencv.core.Mat;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class DrawFace {
    private String sourcePath;
    private Mat source;

    //原图片
    public void setSource(String picPath) {
        this.sourcePath = picPath;
    }
    ///模版匹配，精确度不高
    public void draw() throws IOException {
        //将文件读入为OpenCV的Mat格式
//        source = HighGui.imread(sourcePath);
        String sourcePathParent = sourcePath.substring(0, sourcePath.lastIndexOf(File.separator));
        String fileName = sourcePath.substring(sourcePath.lastIndexOf(File.separator) + 1, sourcePath.length());
        String prefixName = fileName.substring(0, fileName.lastIndexOf("."));
        String suffixName = fileName.substring(fileName.lastIndexOf("."), fileName.length());
        //处理原图为灰度图
        source = Imgcodecs.imread(sourcePath);
//        Mat sourceGray = new Mat();
//        Imgproc.cvtColor(source, sourceGray, Imgproc.COLOR_BGR2GRAY, 0);
//        String sourceGrayPath = sourcePathParent + File.separator + prefixName + "_gray" + suffixName;
//        Imgcodecs.imwrite(sourceGrayPath, sourceGray);

        Imgproc.cvtColor(source, source, Imgproc.COLOR_RGB2GRAY);
        //
        Imgproc.adaptiveThreshold(source, source, 255, Imgproc.ADAPTIVE_THRESH_MEAN_C, Imgproc.THRESH_BINARY_INV, 25, 10);
//        String sourceErPath = sourcePathParent + File.separator + prefixName + "_er" + suffixName;
//        Imgcodecs.imwrite(sourceErPath, source);
        int row = source.rows();
        int col = source.cols();
        int[][] data = new int[row][col];
        String sourceGrayPath = sourcePathParent + File.separator + prefixName + "_ttttt" + ".txt";
        FileWriter out = new FileWriter(sourceGrayPath);  //文件写入流
        System.out.println("===========================");
        for(int i=0;i<row;i++){
            for (int j=0;j<col;j++){
                double[] result = source.get(i,j);
                if(0==result[0]){
                    System.out.print(".");
                    out.write(".");
                }else{
                    out.write(" ");
                    System.out.print(" ");
                }
            }
            out.write("\r\n");
            System.out.println();
        }
        out.flush();
        out.close();
    }
    public static void main(String[] args) throws IOException {
        System.loadLibrary("opencv_java341");

        DrawFace macher = new DrawFace();
        //设置原图
        macher.setSource("C:\\Users\\admin\\Desktop\\1.jpg");

        macher.draw();

    }
}
